
package com.ugoodtech.mdcc.client.controller;

import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.client.service.impl.StationLeanPaintReportServiceImpl;
import com.ugoodtech.mdcc.core.domain.OpenIdParam;
import com.ugoodtech.mdcc.core.repository.OpenIdParamRepository;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 用户Controller：
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-8-28
 * Time: 上午9:58123123
 * <p/>
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/anonymous")
public class AnonymousController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(AnonymousController.class);

    @Value("${wechat.appID}")
    private String appID;
    @Value("${wechat.appSecret}")
    private String appSecret;
    @Autowired
    private OpenIdParamRepository openIdParamRepository;

    @Autowired
    private StationLeanPaintReportServiceImpl stationLeanPaintReportService;




    @RequestMapping(value="/getAccess_token", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getAccess_token() {

        /////////////////
        OpenIdParam openIdParam=openIdParamRepository.findByOpenId("accessToken");
        if((System.currentTimeMillis()-openIdParam.getCreationTime().getTime())<=1000*60*60){
            String body=openIdParam.getAccessTokenBody()               ;
            return JsonResponse.successResponseWithData(body);
        }
        /////////////////

        String weChatUrl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appID+"&secret="+appSecret;
        URLConnection urlConnection = null;
        InputStream inputStream=null;
        try {
            URL url = new URL(weChatUrl);
            urlConnection = url.openConnection();
            urlConnection.setDoOutput(true);
            // 定义待写入数据的内容类型，我们设置为application/x-www-form-urlencoded类型
            urlConnection.setRequestProperty("content-type", "application/json");
            inputStream = urlConnection.getInputStream();
            String encoding = urlConnection.getContentEncoding();
            String body = IOUtils.toString(inputStream, encoding);

            //////////////////////
            openIdParam.setCreationTime(new Date());
            openIdParam.setAccessTokenBody(body);
            openIdParamRepository.save(openIdParam);
            //////////////////////

            return JsonResponse.successResponseWithData(body);
        } catch (IOException e) {
            logger.debug(weChatUrl+" 的请求连接失败");
        }finally{
            try {
                inputStream.close();
            } catch (IOException e) {
                logger.debug("请求为"+weChatUrl+"输入流关闭失败");
            }
        }
        return JsonResponse.errorResponseWithError("","获取失败");
    }




    @RequestMapping(value="/getSignature", method = RequestMethod.GET)
    @ResponseBody
        public Map<String,String> getSignature(String api_ticket, String url) {
            Map<String, String> ret = new HashMap<String, String>();
            String nonce_str = UUID.randomUUID().toString();
            String timestamp =  Long.toString(System.currentTimeMillis() / 1000);
            String string1;
            String signature = "";

            //注意这里参数名必须全部小写，且必须有序
            string1 = "jsapi_ticket=" + api_ticket +
                    "&noncestr=" + nonce_str +
                    "&timestamp=" + timestamp +
                    "&url=" + url;
            System.out.println(string1);

            try
            {
                MessageDigest crypt = MessageDigest.getInstance("SHA-1");
                crypt.reset();
                crypt.update(string1.getBytes("UTF-8"));
                signature = byteToHex(crypt.digest());
            }
            catch (NoSuchAlgorithmException e)
            {
                e.printStackTrace();
            }
            catch (UnsupportedEncodingException e)
            {
                e.printStackTrace();
            }

            ret.put("url", url);
            ret.put("jsapi_ticket", api_ticket);
            ret.put("nonceStr", nonce_str);
            ret.put("timestamp", timestamp);
            ret.put("signature", signature);
            return ret;
        }





//    @RequestMapping(value="/getWeixinTime", method = RequestMethod.GET)
//    @ResponseBody
//    public String getWeixinTime() {
//        String create_timestamp = Long.toString(System.currentTimeMillis() / 1000);
//        return create_timestamp;
//    }
//
//    @RequestMapping(value="/getWeixinString", method = RequestMethod.GET)
//    @ResponseBody
//    public String getWeixinString() {
//        String create_nonce_str = UUID.randomUUID().toString();
//        return create_nonce_str;
//    }


    @RequestMapping(value="/getApi_ticket", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getApi_ticket(String access_token) {

//        /////////////////
//        OpenIdParam openIdParam=openIdParamRepository.findByOpenId("apiTicket");
//        if((System.currentTimeMillis()-openIdParam.getCreationTime().getTime())<=1000*60*60){
//            String body=openIdParam.getAccessTokenBody();
//            return JsonResponse.successResponseWithData(body);
//        }
//        /////////////////

        String weChatUrl="https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token="+access_token;
        URLConnection urlConnection = null;
        InputStream inputStream=null;
        try {
            URL url = new URL(weChatUrl);
            urlConnection = url.openConnection();
            urlConnection.setDoOutput(true);
            // 定义待写入数据的内容类型，我们设置为application/x-www-form-urlencoded类型
            urlConnection.setRequestProperty("content-type", "application/json");
            inputStream = urlConnection.getInputStream();
            String encoding = urlConnection.getContentEncoding();
            String body = IOUtils.toString(inputStream, encoding);

//            //////////////////////
//            openIdParam.setCreationTime(new Date());
//            openIdParam.setAccessTokenBody(body);
//            openIdParamRepository.save(openIdParam);
//            //////////////////////

            return JsonResponse.successResponseWithData(body);
        } catch (IOException e) {
            logger.debug(weChatUrl+" 的请求连接失败");
        }finally{
            try {
                inputStream.close();
            } catch (IOException e) {
                logger.debug("请求为"+weChatUrl+"输入流关闭失败");
            }
        }
        return JsonResponse.errorResponseWithError("","获取失败");
    }






    public  String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    @ApiOperation("测试改善数据")
    @RequestMapping(value = "/updateAnswerDicPhoto", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse updateAnswerDir(Long reportId, MultipartFile file) {
        Long stationId=1L;
        stationLeanPaintReportService.calculateKpiData(reportId,stationId);
        return JsonResponse.successResponseWithData("更新照片成功" + reportId);
    }



}
